package com.zebraphp.devtool.httpUtils.NetOkHttp;

import android.os.Handler;
import android.os.Looper;

import com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder.DownloadBuilder;
import com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder.GetBuilder;
import com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder.PostBuilder;
import com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder.UploadBuilder;

import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;

/**
 * IOkHttp 请求组件，总入口类
 * 基于 OkHttp封装进阶-IOkHttp 改写
 * 参考文章：
 * http://www.jianshu.com/p/219ee2afb4f3
 * http://www.jianshu.com/p/1873287eed87
 */
public class IOkHttp {

    private static OkHttpClient mOk3HttpClient;//OkHttp的组件
    public static Handler mHandlerQueue = new Handler(Looper.getMainLooper());

    public OkHttpClient getOkHttpClient() {
        return mOk3HttpClient;
    }

    /* 构造器 */
    public IOkHttp() {
        this(null);
    }

    /* 构造器 @param okHttpClient custom okhttpclient */
    public IOkHttp(OkHttpClient okHttpClient) {
        if (mOk3HttpClient == null) {
            synchronized (IOkHttp.class) {
                if (mOk3HttpClient == null) {
                    if (okHttpClient == null) {
                        mOk3HttpClient = new OkHttpClient();//使用默认的OkHttpClient配置
                    } else {
                        mOk3HttpClient = okHttpClient;//使用外部传入自行配置的OkHttpClient
                    }
                }
            }
        }
    }

    //获取对应的Request构建器
    public GetBuilder genGetRequest() {
        return new GetBuilder(this);
    }

    //获取对应的Request构建器
    public PostBuilder genPostRequest() {
        return new PostBuilder(this);
    }

    //获取对应的Request构建器
    public UploadBuilder genUploadRequest() {
        return new UploadBuilder(this);
    }

    //获取对应的Request构建器
    public DownloadBuilder genDownloadRequest() {
        return new DownloadBuilder(this);
    }


    /* 通过tag取消对应的请求进程 */
    public void cancel(Object tag) {
        Dispatcher ok3Dispatcher = mOk3HttpClient.dispatcher();

        //遍历所有队列中排队Call请求,取消对应的Call请求
        for (Call call : ok3Dispatcher.queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }

        //遍历所有正在Call请求队列,取消对应的Call请求
        for (Call call : ok3Dispatcher.runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

}
